# deprecated

from querier.esquerier import ElasticSearchQuerier
import querier.weibo.utils as utils
from utils import utils as uc

MINIMUM_SHOULD_MATCH = '5<85% 10<9'
MAX_CHARACTER = 30
CATEGORY_CUTOFF = 0.5


class WeiboPostSearchMiniQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type, nlp_service):
        super(WeiboPostSearchMiniQuerier, self).__init__(es, index, doc_type)
        self.nlp_service = nlp_service

    def _build_query(self, args):
        term = args.get('term', '')
        term = term if term else ''
        filters = args.get('filters', {})
        if filters is None:
            filters = {}
        order = args.get('order_by', utils.ORDER_OVERALL)
        from_ = args.get('from', 0)
        size_ = args.get('size', 10)
        highlight = args.get('highlight', False)

        query = self._gen_query('', term, filters, order, from_, size_, highlight)

        return query, {}, {'order': order}

    def _build_result(self, es_result, param):
        # order = param['order']
        total = es_result['hits']['total']
        posts = []
        for hit in es_result['hits']['hits']:
            posts.append(extract_result(hit))
        return {
            'total': total,
            'posts': posts
        }

    @staticmethod
    def _gen_query(query_keywords, term, filters, order, from_, size_, highlight):
        must_clause = []
        filter_clause = []
        should_clause = []

        if filters:
            utils.get_post_filters(filter_clause, filters)

        if query_keywords.strip():
            must_clause.append(
                {
                    'multi_match': {
                        'analyzer': 'whitespace',
                        'query': query_keywords,
                        'fields': ['keywords', 'seg_weibo_text', 'seg_r_weibo_text'],
                        # 'minimum_should_match': ""
                    }
                }
            )

        if term:
            term = term.strip()
            if len(term) <= 6:
                should_clause.append(
                    {
                        'match_phrase': {
                            "weibo_text": {
                                'query': term[0:MAX_CHARACTER],
                                'boost': 30,
                            },
                        }
                    }
                )
                should_clause.append(
                    {
                        'match_phrase': {
                            "r_weibo_text": {
                                'query': term[0:MAX_CHARACTER],
                                'boost': 30,
                            },
                        }
                    }
                )
            else:
                should_clause.append(
                    {
                        'match': {
                            "weibo_text": {
                                'query': term[0:MAX_CHARACTER],
                                'boost': 30,
                                'minimum_should_match': MINIMUM_SHOULD_MATCH
                            },

                        }
                    }
                )
                should_clause.append(
                    {
                        'match': {
                            "r_weibo_text": {
                                'query': term[0:MAX_CHARACTER],
                                'boost': 30,
                                'minimum_should_match': MINIMUM_SHOULD_MATCH
                            },

                        }
                    }
                )

        query = {"query": {
            "bool": {
                # "must": must_clause,
                # "should": should_clause,
                "filter": filter_clause,
                # "must": {'bool': {}},
                # "minimum_should_match": 1
            }
        }, 'from': from_, 'size': size_}

        if must_clause:
            query['query']['bool']['must'] = must_clause

        if should_clause:
            query['query']['bool']['should'] = should_clause
            query['query']['bool']['minimum_should_match'] = 1

        query = utils.get_post_sort(query, order, term, filters)
        if highlight:
            query['highlight'] = {
                "pre_tags": ["<span class='keyword'>"],
                "post_tags": ["</span>"],
                "fields": {"keywords": {}, "weibo_text": {}, "r_weibo_text": {}}
            }

        return query


def extract_result(hit):
    source_ = hit['_source']
    # score_ = hit['_score']
    res = utils.extract_post_from_source(source_)
    res['category'] = uc.category_smzdm_2_decode(source_['category'])
    keywords = res['keywords']
    highlight = hit.get('highlight')
    if highlight:
        h_keywords = highlight.get('keywords')
        if h_keywords:
            hk2 = [s.replace("<span class='keyword'>", '').replace("</span>", '') for s in h_keywords]
            if hk2:
                h_keywords += [k for k in keywords if k not in hk2][0:10]
                res['keywords'] = h_keywords
        h_weibo_text = highlight.get('weibo_text')
        h_r_weibo_text = highlight.get('r_weibo_text')
        res['summary'] = (source_.get('weibo_text', '') if not h_weibo_text else h_weibo_text[0]) \
                         + '//' + (source_.get('r_weibo_text', '') if not h_r_weibo_text else h_r_weibo_text[0])

    return res
